var vaAccount;
var voAccountList = [];
var vnMaxIndex = 0;
var vnMaxDate = 0;
$(document).ready(function() {

	getDate();
	getInvoiceDataTable();
	$("#number").removeClass("highlight-blue-2");
	$("#total").removeClass("highlight-blue-2");

});
function getInvoiceDataTable() {

	$('#InvoiceDataTable')
			.DataTable(
					{
						"oLanguage" : {
							"oPaginate" : {
								"sFirst" : "หน้าแรก",// ปุ่มกลับมาหน้าแรก
								"sLast" : "หนัาสุดท้าย",// ปุ่มไปหน้าสุดท้าย
								"sNext" : "ถัดไป", // ปุ่มหน้าถัดไป
								"sPrevious" : "ก่อนหน้า" // ปุ่ม กลับ
							},
							"sLengthMenu" : "แสดง _MENU_ รายการ ต่อหน้า",
							"sZeroRecords" : "ไม่พบข้อมูลที่ค้นหา",
							"sInfo" : "แสดง _START_ ถึง _END_ จากทั้งหมด _TOTAL_ รายการ",
							"sEmptyTable" : "ไม่พบรายการข้อมูล",
							"sLoadingRecords" : "ระบบกำลังประมวลผล กรุณารอซักครู่",
							"sProcessing" : "ประมวลผลข้อมูล",
							"sInfoEmpty" : "ไม่พบรายการข้อมูลที่แสดง",
							"sInfoFiltered" : "(จากทั้งหมด _MAX_ รายการ)",
							"sSearch" : "ค้นหา :"
						},
						searching : true,

						"aoColumns" : [
								{
									sClass : "alignCenter",
									"bSortable" : false
								},
								{
									"bSortable" : false
								},
								{
									"bSortable" : false
								},
								{
									sClass : "alignCenter",
									"bSortable" : false,
									"mRender" : function(data, type, full) {
										vnMaxIndex = data[0];
										voAccountList[data[0]] = data[1];
										vaAccount = data[1];
										if (parseInt(data[2]) > vnMaxDate) {
											vnMaxDate = parseInt(data[2]);
										}

										return data[1];
									}
								},
								{
									"bSortable" : false,
									sClass : "alignCenter",
									"mRender" : function(data, type, full) {
										return '<label id="labelPreviousReadDate'
												+ vaAccount
												+ '" style="font-weight: normal;">'
												+ data + '</label>';
									}
								},
								{
									"bSortable" : false,
									sClass : "alignCenter",
									"mRender" : function(data, type, full) {
										return '<label id="labelPreviousReadNumber'
												+ vaAccount
												+ '" style="font-weight: normal;">'
												+ data + '</label>';
									}

								},
								{
									"bSortable" : false,
									sClass : "highlight-blue-2",
									"mRender" : function(data, type, full) {

										return '<input class="form-control" type="text" style="text-align: right;" id="inputCurrentReadNumber'
												+ data
												+ '" onchange="calculateWaterCharge(\''
												+ data + '\')"/>';

									}
								},
								{
									"bSortable" : false,
									sClass : "alignCenter",
									"mRender" : function(data, type, full) {
										return '<label id="labelConsumtion'
												+ data
												+ '" style="font-weight: normal;">0</label>';
									}
								},
								{
									"bSortable" : false,
									sClass : "alignCenter",
									"mRender" : function(data, type, full) {
										return '<input  type="radio" id="inputCalculationNormal'
												+ data
												+ '" name="calculation_'
												+ data
												+ '" checked="checked" value="normal" onchange="calculateWaterCharge(\''
												+ data + '\')"/> ปกติ';
									}
								},
								{
									"bSortable" : false,
									sClass : "alignCenter",
									"mRender" : function(data, type, full) {
										return '<input  type="radio" id="inputCalculationAverage'
												+ data
												+ '" name="calculation_'
												+ data
												+ '" value="average" onchange="calculateWaterCharge(\''
												+ data + '\')"/> เฉลี่ย';
									}
								},
								{
									"bSortable" : false,
									sClass : "highlight-blue-2 alignCenter",
									"mRender" : function(data, type, full) {
										return '<label id="labelTotalAmount'
												+ data
												+ '" style="font-weight: normal;">0.00</label> '
												+ '<input type="hidden" id="inputNewConsumtion'
												+ data
												+ '"/>'
												+ '<input type="hidden" id="inputNewAverageConsumtion'
												+ data
												+ '"/>'
												+ '<input type="hidden" id="inputVatAmount'
												+ data
												+ '"/>'
												+ '<input type="hidden" id="inputWaterCharge'
												+ data
												+ '"/>'
												+ '<input type="hidden" id="inputWaterFee'
												+ data
												+ '"/>'
												+ '<input type="hidden" id="inputBillAmount'
												+ data
												+ '"/>'
												+ '<input type="hidden" id="inputNumberOfDay'
												+ data
												+ '"/>'
												+ '<input type="hidden" id="inputTotalAmount'
												+ data + '"/>';
									}
								} ],
						// "bPaginate" : true,
						// "bInfo" : true,
						"sPaginationType" : "full_numbers",// แสดงตัวแบ่งหน้า
						"bLengthChange" : true, // แสดงจำนวน record
						// ที่จะแสดงในตาราง
						"iDisplayLength" : 10, // กำหนดค่า default ของจำนวน
						// record
						"bScrollCollapse" : true,
						"aLengthMenu" : [ [ 10, 25, 50, 100, -1 ], // จำนวนที่แสดงในตาราง
						[ 10, 25, 50, 100, "ทั้งหมด" ] // จำนวนที่ให้เลือก
						],
						"bProcessing" : true, // เขียนโค้ดโดยระบุให้ไปดึงข้อมูลจากไฟล์
						"bServerSide" : true,
						"sDom" : 'Rlfrtip',
						"sAjaxSource" : "CS33000Srvl?process_type=getDataTable",
						"drawCallback" : function(settings) {

						}

					});
}

function calculateWaterCharge(account) {
	var paCalculation = $("input[name=calculation_" + account + "]:checked")
			.val();
	var pnCurrentReadNumber = parseInt($("#inputCurrentReadNumber" + account)
			.val());
	var pnPreviousReadNumber = parseInt($("#labelPreviousReadNumber" + account)
			.text());
	var pnConsumtion = pnCurrentReadNumber - pnPreviousReadNumber;
	var paPreviousReadDate = $("#labelPreviousReadDate" + account).text();
	var paCurrentReadDate = $("#datetimepicker1").val();
	var paAccount = account;
	$("#buttonOk")
			.replaceWith(
					"<button type=\"button\" class=\"btn btn-primary\" id=\"buttonOk\" onclick=\"getFocus('readNumber','"
							+ account + "')\">ตกลง</button> ");

	if ($("#datetimepicker1").val() == "") {
		$("#inputCurrentReadNumber" + account).val("");
		$('#failDateModal').modal();

		$("#inputCalculationNormal" + account).prop("checked", "checked");

	} else {

		$
				.getJSON(
						'CS33000Srvl?process_type=convertDate',
						{
							paDate : paCurrentReadDate,
							url_address:$("#url_address").val(),
							agent_browser:$("#agent_browser").val()
						},
						function(result) {
							if (parseInt(result.paDate) >= vnMaxDate) {
								if ($("#inputCurrentReadNumber" + account)
										.val() == "") { // && paCalculation !=
														// "average"
									if (paCalculation == "average") {
										$("#inputCalculationNormal" + account)
												.prop("checked", "checked");
										validateCurrentReadNumber("number",
												account);
									} else {
										$("#inputCurrentReadNumber" + account)
												.val("");
										$("#labelTotalAmount" + account).text(
												"0.00");
										$("#labelConsumtion" + account).text(
												"0");
									}

								} else if (isNaN($(
										"#inputCurrentReadNumber" + account)
										.val()) == true) {
									validateCurrentReadNumber("number", account);
								} else if ($(
										"#inputCurrentReadNumber" + account)
										.val().indexOf(".") != -1) {
									validateCurrentReadNumber("number", account);
								} else if (parseInt($(
										"#inputCurrentReadNumber" + account)
										.val()) < pnPreviousReadNumber) {
									validateCurrentReadNumber("number", account);
								} else {
									$
											.getJSON(
													'CS33000Srvl?process_type=calculate',
													{
														paCalculation : paCalculation,
														pnConsumtion : pnConsumtion,
														paAccount : paAccount,
														paPreviousReadDate : paPreviousReadDate,
														paCurrentReadDate : paCurrentReadDate,
														url_address:$("#url_address").val(),
														agent_browser:$("#agent_browser").val()
													},
													function(result) {

														$(
																"#labelTotalAmount"
																		+ account)
																.text(
																		result.TotalAmount);
														$(
																"#labelConsumtion"
																		+ account)
																.text(
																		pnConsumtion);

														$(
																"#inputNewConsumtion"
																		+ account)
																.val(
																		result.NewConsumtion);
														$(
																"#inputNewAverageConsumtion"
																		+ account)
																.val(
																		result.NewAverageConsumtion);
														$(
																"#inputVatAmount"
																		+ account)
																.val(
																		result.VatAmount);
														$(
																"#inputWaterCharge"
																		+ account)
																.val(
																		result.WaterCharge);
														$(
																"#inputWaterFee"
																		+ account)
																.val(
																		result.WaterFee);
														$(
																"#inputBillAmount"
																		+ account)
																.val(
																		result.BillAmount);
														$(
																"#inputNumberOfDay"
																		+ account)
																.val(
																		result.NumberOfDay);
														$(
																"#inputTotalAmount"
																		+ account)
																.val(
																		result.TotalAmount);

													});

								}

							} else {
								validateCurrentReadNumber("date", account);
							}
						});

	}

}
function iteration() {
	var oTable = $('#InvoiceDataTable').dataTable();

	if (oTable.fnGetData().length > 0) {
		for (var i = vnMaxIndex; i >= 0; i--) {
			calculateWaterCharge(voAccountList[i]);
		}
	}

}
function confirmSaveData() {
	$('#confirmSaveData').modal();
}
function saveData() {
	var pnCurrentReadNumber;
	var pnNewConsumtion;
	var pnNewAverageConsumtion;
	var pnVatAmount;
	var pnWaterCharge;
	var pnWaterFee;
	var pnBillAmount;
	var pnNumberOfDay;
	var pnTotalAmount;
	var pnZoneId = document.getElementById("inputZone").value;
	var pnRouteId = document.getElementById("inputRoute").value;
	var paCurrentReadDate = $("#datetimepicker1").val();

	for (var i = 0; i <= vnMaxIndex; i++) {

		pnCurrentReadNumber = $("#inputCurrentReadNumber" + voAccountList[i]).val();
		pnNewConsumtion = $("#inputNewConsumtion" + voAccountList[i]).val();
		pnNewAverageConsumtion = $("#inputNewAverageConsumtion" + voAccountList[i]).val();
		pnVatAmount = $("#inputVatAmount" + voAccountList[i]).val();
		pnWaterCharge = $("#inputWaterCharge" + voAccountList[i]).val();
		pnWaterFee = $("#inputWaterFee" + voAccountList[i]).val();
		pnBillAmount = $("#inputBillAmount" + voAccountList[i]).val();
		pnNumberOfDay = $("#inputNumberOfDay" + voAccountList[i]).val();
		pnTotalAmount = $("#inputTotalAmount" + voAccountList[i]).val();
		
		$.ajax({           	
    		url : "CS33000Srvl?process_type=saveData",
    		type : "POST",
    		data: {
    			pnCurrentReadNumber : pnCurrentReadNumber,
    			pnNewConsumtion : pnNewConsumtion,
    			pnNewAverageConsumtion : pnNewAverageConsumtion,
    			pnVatAmount : pnVatAmount,
    			pnWaterCharge : pnWaterCharge,
    			pnWaterFee : pnWaterFee,
    			pnBillAmount : pnBillAmount,
    			pnNumberOfDay : pnNumberOfDay,
    			pnTotalAmount : pnTotalAmount,
    			paAccount : voAccountList[i],
    			pnZoneId : pnZoneId,
    			pnRouteId : pnRouteId,
    			paCurrentReadDate : paCurrentReadDate,
    			url_address:$("#url_address").val(),
    			agent_browser:$("#agent_browser").val()
    			},
    		async : false,
    		success : function(result) { 
    			if(i == vnMaxIndex){
    				$('#InvoiceDataTable').DataTable().draw();	
    			}
    		}
		
		});
	}

}
function validateCurrentReadNumber(validate, account) {
	if (validate == "number") {
		$('#failReadNumberModal').modal();
	} else if (validate == "date") {

		$('#failDateModal').modal();
	}
	$("#inputCalculationNormal" + account).prop("checked", "checked");
	$("#inputCurrentReadNumber" + account).val("");
	$("#labelTotalAmount" + account).text("0.00");
	$("#labelConsumtion" + account).text("0");
}
function getDate() {
	$.getJSON('CS33000Srvl?process_type=getDate', {	url_address:$("#url_address").val(), agent_browser:$("#agent_browser").val()}, function(result) {
		$("#inputMaxMonth").text(result.maxMonth);
		$("#inputMaxYear").text(result.maxYear);
	});
}

function searchData() {

	var vnZoneId = document.getElementById("inputZone").value;
	var vnRouteId = document.getElementById("inputRoute").value;
	var vaAccount = document.getElementById("inputAccount").value;

	if (vaAccount == "") {
		if (vnZoneId == "" || vnRouteId == "") {
			$('#failZoneModal').modal();
		} else {

			$('#InvoiceDataTable').DataTable().column(0).search(vnZoneId);
			$('#InvoiceDataTable').DataTable().column(1).search(vnRouteId);
			$('#InvoiceDataTable').DataTable().column(2).search(vaAccount);
			$('#InvoiceDataTable').DataTable().draw();

		}

	} else {

		$('#InvoiceDataTable').DataTable().column(0).search(vnZoneId);
		$('#InvoiceDataTable').DataTable().column(1).search(vnRouteId);
		$('#InvoiceDataTable').DataTable().column(2).search(vaAccount);
		$('#InvoiceDataTable').DataTable().draw();

	}

}
function getFocus(elemId, account) {

	$(".close").trigger("click");
	if (elemId == "datetimepicker1") {
		document.getElementById("datetimepicker1").focus();
	} else if (elemId == 'readNumber') {
		document.getElementById("inputCurrentReadNumber" + account).focus();
	} else {

		var vnZoneId = document.getElementById("inputZone").value;
		var vnRouteId = document.getElementById("inputRoute").value;
		if (vnZoneId == "") {
			document.getElementById("inputZone").focus();
		} else if (vnRouteId == "") {
			document.getElementById("inputRoute").focus();
		}

	}

}
